﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SecretDemo
{
    public class JWTService
    {
        private string _key;
        public JWTService(string key) { 
            _key = key;
        }
        /// <summary>
        /// 通过通过用户信息创建token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GenarateToken(User user)
        {
            //载荷， 用户信息
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,user.Account)
            };
            //令牌密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key));
            //令牌签名
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: null, audience: null,
                claims: claims, expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);
            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
